<template>
    <div class="register-container">
        <el-form :model="form" ref="form" label-width="100px" class="register-form">
            <el-form-item label="昵称">
                <el-input type="text" v-model="nickname" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
                <el-input v-model="email" type="text" show-word-limit></el-input>
            </el-form-item>
            <el-form-item>
                <el-button v-if="countdown>=5" @click="sendEmailCode">发送邮箱验证码</el-button>
                <div v-else>验证码倒计时：{{ countdown }}</div>
            </el-form-item>
            <el-form-item label="邮箱验证码">
                <el-input v-model="emailCode" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="密码">
                <el-input v-model="password" show-word-limit type="password"  show-password/>
            </el-form-item>
            <el-form-item label="个性宣言" >
                <el-input type="textarea" v-model="introduce" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="头像" >
                <el-upload class="avatar-uploader" :action="uploadurl" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm">注册</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElNotification } from 'element-plus';
import { baseURL } from '@/baseurl'
import { toast } from '@/composables/utils';
import { getcaptcha,register } from '@/apis/user';
import { useRouter } from 'vue-router'
import { set } from '@vueuse/core';

const nickname = ref('')
const email = ref('')
const password = ref('')
const introduce = ref('')
const emailCode = ref('')
const imageUrl = ref('')
const router = useRouter()
const upavatar = ref('')
const uploadurl = ref('')
const countdown = ref(5)

let interval = null;

const sendEmailCode = () => {
    if (email.value === '') {
        toast('请输入邮箱', 'error')
        return
    }

    if (interval) {
        clearInterval(interval);  // 清除之前的倒计时
    }
    countdown.value = 5;  // 重置倒计时
    interval = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--;
        } else {
            clearInterval(interval);
            countdown.value = 5;  // 倒计时结束后重新赋值为5
        }
    }, 1000);


    getcaptcha(email.value).then(res => {
        console.log("发送成功，回显结果是", res);
        toast(res.msg)
    })


};

// 文件上传成功时触发
const handleAvatarSuccess = (response, uploadFile) => {
    console.log("头像上传成功！", response.imgurl);
    console.log("头像上传成功！", uploadFile.raw);
    upavatar.value = response.imgurl
    imageUrl.value = baseURL + response.imgurl
    console.log("拼接后的图片地址是：", imageUrl.value);
    // imageUrl.value = URL.createObjectURL(uploadFile.raw)
}


const beforeAvatarUpload = (file) => {
    uploadurl.value = baseURL + 'api/upavatar'
    const isJPG = file.type === 'image/jpeg';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
        ElNotification({
            title: '错误',
            message: '上传头像图片只能是 JPG 格式!',
            type: 'error'
        });
    }
    if (!isLt2M) {
        ElNotification({
            title: '错误',
            message: '上传头像图片大小不能超过 2MB!',
            type: 'error'
        });
    }
    return isJPG && isLt2M;
};

const submitForm = () => {
   if (validateForm()) {
    // 这里校验成功
    console.log("校验成功");
    register({
        nickname: nickname.value,
        email: email.value,
        captcha: emailCode.value,
        password: password.value,
        intruduce: introduce.value,
        avatar: upavatar.value
    }).then(res => {
        toast('注册成功', 'success');
        // 跳转到登录界面
         router.replace({ path: '/login' })      // 跳转登录页，防止用户返回
    })

   }

};

const validateForm = () => {
  if (!nickname.value) {
    toast('昵称不能为空', 'error');
    return false;
  }
  if (!email.value) {
    toast('邮箱不能为空', 'error');
    return false;
  }
  // 简单的邮箱格式验证
  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailPattern.test(email.value)) {
    toast('请输入有效的邮箱地址', 'error');
    return false;
  }
  if (!emailCode.value) {
    toast('邮箱验证码不能为空', 'error');
    return false;
  }
  if (!password.value) {
    toast('密码不能为空', 'error');
    return false;
  }
  if (password.value.length < 6) {
    toast('密码长度不能少于6位', 'error');
    return false;
  }
  if (!introduce.value) {
    toast('个性宣言不能为空', 'error');
    return false;
  }
  if (!imageUrl.value) {
    toast('请上传头像', 'error');
    return false;
  }
  return true;
};
</script>

<style scoped>
.register-container {
    max-width: 500px;
    margin: 50px auto;
    padding: 20px;
    border: 1px solid #dcdcdc;
    border-radius: 10px;
    background-color: #fff;
}


.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.avatar {
    width: 120px;
    height: 120px;
    display: block;
}
</style>